package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.common.utils.RandomUtils;
import com.sangmo.fts.process.storage.model.CsfInbound;
import com.sangmo.fts.process.storage.model.CsfOutbound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class CsfInboundService extends DelegateViewService<CsfInbound> {

    @Autowired
    private CsfInboundEntityService csfInboundEntityService;

    @Autowired
    private CsfLadingBillService csfLadingBillService;

    @Override
    protected ViewService<CsfInbound> getEntityService() {
        return csfInboundEntityService;
    }

    public void receive(Long inboundId) {
        CsfInbound inbound = this.get(inboundId);
        if (!CsfInbound.States.DISPATCHED.equals(inbound.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfInbound.receive.state.wrong");
        }
        inbound.setState(CsfInbound.States.PENDING);
        this.save(inbound);
    }

    public void store(Long ifInboundId) {
        CsfInbound inbound = this.get(ifInboundId);
        if (!CsfInbound.States.PENDING.equals(inbound.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfInbound.store.state.wrong");
        }
        inbound.setCode(RandomUtils.generateRandomNum(8));
        inbound.setState(CsfInbound.States.COMPLETED);
        inbound.setInDate(new Date());
        inbound.setConfirmedBy((Long) UserSession.getUserInterface().getId());
        this.save(inbound);
    }

    public PageResult listItemsByPage(Long id, PageSearch ps) {
        CsfInbound inbound = this.get(id);
        return csfLadingBillService.listItemsByPage(inbound.getBillId(), ps);
    }
}
